package com.smit.icastplus.ssdp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * 单播socket
 */
class SSDPDatagramSocket extends DatagramSocket {
    private byte[] receiveBuffer = new byte[SSDPConstants.MAX_LEN];

    /**
     * 构造函数
     * @throws IOException 绑定端口失败
     */
    public SSDPDatagramSocket() throws IOException {
        super(SSDPConstants.SSDP_PORT);
        setSoTimeout(SSDPConstants.TIMEOUT);
    }

    /**
     * @param message 消息内容
     * @param host    目标地址
     * @throws IOException 发送异常
     */
    public void sendMessage(String message, String host) throws IOException {
        DatagramPacket datagram = new DatagramPacket(message.getBytes("UTF-8"), message.length(),
                InetAddress.getByName(host), SSDPConstants.SSDP_PORT);

        this.send(datagram);
    }

    /**
     * @return 数据报
     * @throws IOException 接收异常
     */
    public DatagramPacket receiveMessage() throws IOException {
        DatagramPacket datagram = new DatagramPacket(receiveBuffer, receiveBuffer.length);
        this.receive(datagram);
        return datagram;
    }

    /**
     * 关闭socket
     */
    public void closeSocket() {
        this.close();
        receiveBuffer = null;
    }
}
